import axios from 'axios'
// import { getXSRFToken } from '@/utils/auth'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // process.env.VUE_APP_BASE_API, // url = base url + request url
  // http://192.168.0.69:20002
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
      // config.headers['X-XSRF-TOKEN'] = `${store.getters.token}`
      // config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log(response, '-----------------------------response')
    if (response.headers['content-disposition']) {
      let filename = ''
      const disposition = response.headers['content-disposition']
      if (disposition && disposition.indexOf('attachment') !== -1) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        var matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
        }
      }
      // store.commit('settings/getFilename', decodeURIComponent(filename.substr(filename.indexOf('=') + 1)))
      // var xhr = new XMLHttpRequest()
      // console.log(xhr, '-----------------------xhr');
      // var filename = ''
      // var disposition = xhr.getResponseHeader('content-Disposition')
      // console.log(disposition, '-----------------------------disposition')
      // if (disposition && disposition.indexOf('attachment') !== -1) {
      //   var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
      //   var matches = filenameRegex.exec(disposition)
      //   if (matches != null && matches[1]) {
      //     filename = matches[1].replace(/['"]/g, '')
      //   }
      // }
      console.log(filename, '-------------------filename');
      store.commit('settings/getFilename', decodeURIComponent(filename))
    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (response.config && response.config.responseType === 'blob') {
      return res
    }
    if (res.status !== 200 && (res.error && res.error.code !== 423)) {
      Message({
        message: res.error.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 401) {
        // to re-login
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
        // MessageBox.confirm('您已退出登录，您可以取消以留在此页面，或再次登录', '退出登录', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
      }
      if (response.config && response.config.needError) {
        return res
      } else {
        // this.$router.push(`/login?redirect=${this.$route.fullPath}`)
        return Promise.reject(new Error(res.error.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
